# Maintainer: Marian Buschsieweke <marian.buschsieweke@ovgu.de>

_targets="
	arm-none-eabi
	riscv-none-elf
	"
pkgname=picolibc
pkgver=1.8.2
_gccver=13.1.0
pkgrel=0
pkgdesc="A C standard library based on newlib with focus on compact size"
url="https://github.com/picolibc/picolibc"
makedepends="meson"
# limited by newlib
arch="aarch64 ppc64le x86_64 x86"
license="GPL-2.0-only AND LGPL-2.1-only AND 0BSD AND BSD-3-Clause AND GPL-3.0-only AND LGPL-3.0-only"
source="$pkgname-$pkgver.tar.xz::https://github.com/picolibc/picolibc/releases/download/$pkgver/picolibc-$pkgver.tar.xz"
options="!check"

for target in $_targets; do
	targetnorm="${target//-/_}"
	subpackages="picolibc-$target:$targetnorm $subpackages"
	makedepends="binutils-$target gcc-$target~$_gccver newlib-$target $makedepends"
done

prepare() {
	default_prepare

	# Handle mismatch of target triples
	mv "$builddir/scripts/cross-riscv64-unknown-elf.txt" \
		"$builddir/scripts/cross-riscv-none-elf.txt"
	sed -e 's/riscv64-unknown-elf/riscv-none-elf/g' \
		-i "$builddir/scripts/cross-riscv-none-elf.txt"
}

build() {
	for target in $_targets; do
		# CFLAGS and LDFLAGS from the host (Linux) do not necessarily make sense
		# for the target (bare metal MCU)
		unset CFLAGS
		unset LDFLAGS
		# cannot use abuild-meson here, as target != host
		meson \
			--prefix=/usr/ \
			--buildtype=plain \
			--cross-file=scripts/cross-$target.txt \
			-Dincludedir=picolibc/$target/include \
			-Dlibdir=picolibc/$target/lib \
			. build-$target
		meson compile -C build-$target
	done
}

package() {
	for target in $_targets; do
		depends="$depends picolibc-$target"
	done
	mkdir -p "$pkgdir"
}

_install_subpkg() {
	target="${subpkgname#picolibc-}"
	pkgdesc="A C standard library based on newlib with focus on compact size for $target"
	depends="binutils-$target gcc-$target~$_gccver $depends"

	DESTDIR="$subpkgdir" meson install -C "$builddir/build-$target"
}

arm_none_eabi() {
	_install_subpkg
}

riscv_none_elf() {
	_install_subpkg
}

sha512sums="
c2a0a28084912a7c43dce450d5eb403f52b4fbab7f9bd54946f72a5c9e2aba886afc3b6bd3bdbdc52978fef9453b65710339ec52419bae171e3746c1a0390d3b  picolibc-1.8.2.tar.xz
"
